<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\Products;
use App\Models\Coupon;
use App\Models\Product;
use App\Services\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Models\CustomerCoupon;
use Illuminate\Support\Facades\Auth;

class CouponController extends Controller
{
    /**
     * 优惠商品列表
     */
    public function index(Request $request)
    {
        $coupons = Coupon::query()
            ->where('enabled', 1)
            ->get();

        $category = collect();
        $product = collect();
        foreach ($coupons as $coupon) {
            $category = $category->merge($coupon->categories->pluck('id'))->unique();
            $product = $product->merge($coupon->products->pluck('id'))->unique();
        }

        $request->request->add([
            'categories' => json_encode($category),
            'ids' => json_encode($product)
        ]);

        $proxy = Request::create(route('api.product.index'), "post");

        return \Route::dispatch($proxy);
    }

    /**
     * 领取优惠券
     */
    public function receive(Request $request)
    {
        $code = $request->post('coupon_code');

        $coupon = Coupon::whereCode($code)->first();

        if (!$coupon) {
            return Api::msg('api.coupon.not_found');
        }

        if ($coupon->total <= $coupon->used) {
            return Api::msg('api.coupon.not_enough');
        }

        DB::transaction(function () use ($coupon) {
            $coupon->increment('used');
            CustomerCoupon::hasReceiveCoupon(Auth::user(), $coupon);
        });

        return Api::success();
    }
}
